package com.gxa.weixing.pc.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.gxa.weixing.core.common.JsonResult;
import com.gxa.weixing.core.exception.BusinessException;
import com.gxa.weixing.core.pojo.Export;
import com.gxa.weixing.core.pojo.Logistics;
import com.gxa.weixing.pc.service.LogisticsService;
import com.gxa.weixing.pc.service.OrderManagerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 18380
 */
@RestController
@RequestMapping("/orderManager")
@Api(tags = "订单管理")
public class OrderManagerController {

    @Autowired
    private OrderManagerService orderManagerService;
    @Autowired
    private LogisticsService logisticsService;

    @ApiOperation("门店立购")
    @PostMapping("/store")
    public Map<String, Object> storeOrder(@RequestBody Map<String, Object> map) throws Exception {

        List<Map<String, Object>> maps = orderManagerService.orderList(map);
        double total = 0.00;
        for (Map<String, Object> stringObjectMap : maps) {
            double total1 = Double.parseDouble(stringObjectMap.get("total").toString());
            total = total + total1;
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(maps);
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(maps);
        jsonResult.put("total", total);
        return jsonResult.getDataMap();
    }

//    @ApiOperation("商品寄送")
//    @GetMapping("/sendByPost")
//    @ApiImplicitParam(name = "map", value = "map", paramType = "body", dataType = "Map")
//    public Map<String, Object> sendByPost(Map<String, Object> map) {
//        List<Map<String, Object>> maps = orderManagerService.orderList(map);
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.setCode("200");
//        jsonResult.setMsg("查询成功");
//        jsonResult.setData(maps);
//        return jsonResult.getDataMap();
//    }

//    @ApiOperation("订单详情")
//    @GetMapping("/order")
//    public Map<String, Object> order(Map<String, Object> map) {
//        List<Map<String, Object>> maps = orderManagerService.orderList(map);
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.setCode("200");
//        jsonResult.setMsg("查询成功");
//        jsonResult.setData(maps);
//        return jsonResult.getDataMap();
//    }

//    @ApiOperation("税前毛利")
//    @GetMapping("/profit")
//    @ApiImplicitParam(name = "map", value = "map", paramType = "body", dataType = "Map")
//    public Map<String, Object> profit(Map<String, Object> map) {
//        orderManagerService.orderList(map);
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.setCode("200");
//        jsonResult.setMsg("查询成功");
//        jsonResult.setData(map);
//        return jsonResult.getDataMap();
//    }

//    @GetMapping("/reward")
//    @ApiOperation("门店订单")
//    @ApiImplicitParam(name = "map", value = "map", paramType = "body", dataType = "Map")
//    public Map<String, Object> reward(Map<String, Object> map) {
//        orderManagerService.orderList(map);
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.setCode("200");
//        jsonResult.setMsg("查询成功");
//        jsonResult.setData(map);
//        return jsonResult.getDataMap();
//    }


    @PostMapping("/findById")
    @ApiOperation("查询单个订单详情")
    @ApiImplicitParam(name = "id", value = "id")
    public Map<String, Object> findById(String id) throws Exception {
        List<Map<String, Object>>  byId = orderManagerService.findById(id);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("修改成功");
        jsonResult.setData(byId);
        return jsonResult.getDataMap();
    }


    @PostMapping("/update")
    @ApiOperation("修改订单物流信息")
    @ApiImplicitParam(name = "logistics", value = "logistics", paramType = "body", dataType = "Logistics")
    public Map<String, Object> updateLogistics(Logistics logistics) throws Exception {
        logisticsService.updateLogistics(logistics);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("修改成功");
        return jsonResult.getDataMap();
    }

    @PostMapping("/export")
    @ApiOperation(value = "导出")
    public void export(
            @RequestBody Map<String, Object> map, HttpServletResponse response) throws Exception {
        // 查询到需要导出的集合
        List<Map<String, Object>> maps = orderManagerService.orderList(map);
        // 创建一个空的集合 泛型为被导出的实体类
        List<Export> exportList = new ArrayList<>();
//        遍历查询到的集合
        for (Map<String, Object> stringObjectMap : maps) {
            // 将map转换为JSON字符串
            String jsonString = JSONUtils.toJSONString(stringObjectMap);
            // 将JSON字符串转化为对象
            Export export = JSON.parseObject(jsonString, Export.class);
            // 将对象装入新创建的集合
            exportList.add(export);
        }
        System.out.println(exportList);
        // 工作簿对象(excel文件对象)
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("订单展示表");
        String fileName = "订单表.xls";
        // 将文件名中的中文部分被URL编码后的内容进行解析, 最终还是显示为中文状态
        fileName = URLEncoder.encode(fileName, "utf-8");

        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = {
                "编号",
                "订单号",
                "商品名称",
                "商价格",
                "供应商",
                "总价",
                "用户邀请码",
                "订单状态",
                "配送方式",
                "订单号",
                "下单时间",
                "运单号",
                "取件码",
                "收货手机号"};

        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            //先把文字转换为标准的富文本格式
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把转换后的字段名添加到表头行上
            cell.setCellValue(text);
        }
        //准备将时间格式处理为标准日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 添加数据行:
        int rowNum = 1;
        System.out.println(exportList);
        for (Export export : exportList) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(rowNum);
            dataRow.createCell(1).setCellValue(export.getOrderId());
            dataRow.createCell(2).setCellValue(export.getGoodsName());
            dataRow.createCell(3).setCellValue(export.getGoodsPrice());
            dataRow.createCell(4).setCellValue(export.getGoodsNumber());
            dataRow.createCell(5).setCellValue(export.getSupplierName());
            dataRow.createCell(6).setCellValue(export.getUserInvitationCode());
            dataRow.createCell(7).setCellValue(export.getStatus());
            dataRow.createCell(8).setCellValue(export.getLogisticsType());
            dataRow.createCell(9).setCellValue(export.getOrderNo());
            dataRow.createCell(10).setCellValue(dateFormat.format(export.getOrderTime()));
            dataRow.createCell(11).setCellValue(export.getTrackNo());
            dataRow.createCell(12).setCellValue(export.getTakeCode());
            dataRow.createCell(13).setCellValue(export.getAddressPhone());
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //告诉浏览器, 以附件方式打开,而不是页面上浏览
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
}
